package com.twotwoshop.service.goods.service.Impl;


import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twotwoshop.commom.redis.RedisConstants;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.goods.pojo.Product;
import com.twotwoshop.domin.goods.pojo.ProductComment;
import com.twotwoshop.domin.goods.pojo.ProductFavorite;
import com.twotwoshop.domin.goods.vos.ProductVo;
import com.twotwoshop.domin.user.pojos.ApUser;
import com.twotwoshop.fegin.api.user.IUserClient;
import com.twotwoshop.service.goods.mapper.ProductFavoriteMapper;
import com.twotwoshop.service.goods.mapper.ProductMapper;
import com.twotwoshop.service.goods.service.ProductFavoriteService;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ProductFavoriteServiceImpl extends ServiceImpl<ProductFavoriteMapper, ProductFavorite> implements ProductFavoriteService {


    private final ProductFavoriteMapper productFavoriteMapper;

    private final StringRedisTemplate stringRedisTemplate;

    private final ProductMapper productMapper;

    private final IUserClient userClient;


    /**
     * 收藏
     *
     * @param productFavorite
     * @return
     */
    @Override
    public ResponseResult addFavorite(ProductFavorite productFavorite) {

        //1.检查参数
        if (productFavorite.getProductId() == null || productFavorite.getProductId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取用户id
        long userId = AppThreadLocalUtil.getUser().getId().longValue();

        productFavorite.setUserId(userId);
        productFavorite.setCreatedTime(LocalDateTime.now());

        //保存点赞历史到Redis
        Boolean add = stringRedisTemplate.opsForZSet().add(RedisConstants.GOODS_FAVOURITE_HISTORY_KEY + userId, String.valueOf(productFavorite.getProductId()), System.currentTimeMillis());

        if (!add) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //异步保存商品收藏数据
        upFavourite(productFavorite.getProductId(),productFavorite.getUserId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }




    /**
     * 取消收藏
     *
     * @param productFavorite
     * @return
     */
    @Override
    public ResponseResult cancelFavorite(ProductFavorite productFavorite) {


        //1.检查参数
        if (productFavorite.getProductId() == null || productFavorite.getProductId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取用户id
        long userId = AppThreadLocalUtil.getUser().getId().longValue();


        //3.查询当前收藏是否存在
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.GOODS_FAVOURITE_HISTORY_KEY + userId, String.valueOf(productFavorite.getProductId()));
        if (score == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //4.取消收藏
        Long remove = stringRedisTemplate.opsForZSet().remove(RedisConstants.GOODS_FAVOURITE_HISTORY_KEY + userId, String.valueOf(productFavorite.getProductId()));
        if (remove == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"取消收藏失败");
        }

        //异步删除商品被该用户收藏信息
        deleteFavourite(productFavorite.getProductId(),userId);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 异步更新商品的收藏量
     *
     * @param @return
     */
    @Override
    @Async("twotwoExecutor")
    public void upFavourite(Long productId,Long userId) {

        log.info("线程池异步更新商品的收藏量");


        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.GOODS_FAVOURITE_KEY + productId, String.valueOf(userId));

        //如果未收藏
        if (score == null) {

            //redis异步更新商品收藏次数
            stringRedisTemplate.opsForZSet().incrementScore(
                    RedisConstants.GOODS_FAVOURITE_KEY + productId,
                    userId.toString(),
                    1
            );

        }else {
            log.info("该用户已收藏");
            return;
        }

    }

    /**
     * 异步删除商品的收藏量
     *
     * @param @return
     */
    @Override
    @Async("twotwoExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void deleteFavourite(Long productId,Long userId) {

        log.info("线程池异步删除商品的收藏量");


        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.GOODS_FAVOURITE_KEY + productId, String.valueOf(userId));

        //如果未收藏
        if (score != null) {
            //redis异步删除该用户的收藏
            stringRedisTemplate.opsForZSet().remove(RedisConstants.GOODS_FAVOURITE_KEY + productId, String.valueOf(userId));

        }else {
            log.info("该用户不存在");
            return;
        }

        //数据库删除该收藏信息
        LambdaQueryWrapper<ProductFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductFavorite::getProductId, productId);
        queryWrapper.eq(ProductFavorite::getUserId, userId);

        ProductFavorite productFavorite = productFavoriteMapper.selectOne(queryWrapper);
        if (productFavorite == null) {
            log.info("该收藏信息不存在");
        }

        int i = productFavoriteMapper.delete(queryWrapper);
        if (i > 0) {
            log.info("删除商品收藏信息成功");
        }

    }



    /**
     * 查询收藏商品
     *
     * @return
     */
    @Override
    public ResponseResult selectFavorite() {

        //2.获取用户
        Integer userId = AppThreadLocalUtil.getUser().getId();

        //用户搜藏的商品全部id集合
        List<Long> productIdList;

        //先去Redis中查询数据
        Set<String> productIdLists = stringRedisTemplate.opsForZSet().range(RedisConstants.GOODS_FAVOURITE_HISTORY_KEY + userId, 0, -1);
        if (productIdLists != null && productIdLists.size() > 0) {

            productIdList = productIdLists.stream().map(Long::valueOf).collect(Collectors.toList());

        }else {
            //数据库兜底查询
            LambdaQueryWrapper<ProductFavorite> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductFavorite::getUserId, userId);
            queryWrapper.orderByDesc(ProductFavorite::getCreatedTime);

            //3.查询该用户收藏的商品id
            List<ProductFavorite> favorites = productFavoriteMapper.selectList(queryWrapper);

            //判空
            if (favorites == null || favorites.size() == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            productIdList = favorites.stream().map(ProductFavorite::getProductId).collect(Collectors.toList());

        }






        List<Product> favoritesProductedLists = productMapper.selectBatchIds(productIdList);
        if (favoritesProductedLists == null || favoritesProductedLists.size() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }


  /*      List<Product> voList=new ArrayList<>();

        for (Product product : favoritesProductedLists) {
            ProductVo vo = new ProductVo();
            BeanUtils.copyProperties(product, vo);

            //将图片路径转化为集合
            List<String> imageList = Arrays.stream(product.getImages().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());

            vo.setImages(imageList);

            //查询发布商品人的昵称和头像
            ResponseResult userInfo = userClient.getUserInfoById(product.getUserId());
            if (userInfo.getCode()==200){
                //拿取用户信息
                String jsonString = JSON.toJSONString(userInfo.getData());
                ApUser user = JSONUtil.toBean(jsonString, ApUser.class);

                //设置用户的名称和头像
                vo.setName(user.getName());
                vo.setImage(user.getImage());
                vo.setUserId(user.getId().longValue());
            }

            voList.add(product);

        }*/

        return ResponseResult.okResult(favoritesProductedLists);
    }

    /**
     * 检查收藏状态
     *
     * @param productId
     * @return
     */
    @Override
    public ResponseResult checkFavorite(Long productId) {

        //1.参数校验
        if (productId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取用户
        Integer userId = AppThreadLocalUtil.getUser().getId();

        //3.查询当前收藏是否存在
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.GOODS_FAVOURITE_HISTORY_KEY + userId, String.valueOf(productId));
        if (score == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }



        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}